<?php

class GroupMembersModel
{
	private $groupMembersKeyPrefix =   'GMM/';
	private $groupKeyPrefix        =   'GI/';
	private $diaryListCacheModel;
	private $grouInfoModel;
	
	public function __construct()/*{{{*/
	{
		$this->diaryListCacheModel      =   new DiaryListCacheModel();
		$this->grouInfoModel            =   new GroupInfoModel();
	}/*}}}*/

	/**
	 * 用户加入圈子
	 * @param unknown $info
	 * @return boolean|Ambigous <unknown, boolean, number, resource>
	 */
	public function addMembers($info)/*{{{*/
	{	
		if (empty($info['gid']) || empty($info['uid']))
		{
			AC::$errorNo    =   'GMM001';
			return FALSE;
		}

		$data = array();
		$data['uid']        =   intval($info['uid']);
		$data['gid']        =   intval($info['gid']);
		$data['time']   	=   AC::SERVER_TIME;
		$data['ftime']   	=   AC::SERVER_TIME;
		$data['status']     =   '0';
		$data['gtype']      =   intval($info['gtype']) ? intval($info['gtype']) : 0;
		
		$userGroup = $this->getGroupMember($data['uid'], $data['gid'], $data['gtype']);
		if (!empty($userGroup)){
			$result = $this->setGroupMember($data);
			return $result;
		}
		
		$key    =   $this->groupMembersKeyPrefix. $info['uid'];
		$result =   Storage::addData($key, $data);
		if (!$result){
			return false;
		}
		$this->diaryListCacheModel->addGroupUser($data['gid'], $data['uid']);
		return true;
	}/*}}}*/
	
	// 加入或退出圈子
	public function setGroupMember($info)/*{{{*/
	{
		if (empty($info['gid']) || empty($info['uid']))
		{
			AC::$errorNo    =   'GMM001';
			return FALSE;
		}
		
		$data = array();
		$data['uid']		=   intval($info['uid']);
		$data['gid']		=   intval($info['gid']);
		$data['status']		=   intval($info['status']);
		$data['time']		=   AC::SERVER_TIME;
		
		$key    =   $this->groupMembersKeyPrefix. $info['uid'];
		$where  =   array('gid' => $info['gid'],'uid' => $info['uid'],'gtype' => $info['gtype']);
		$result =   Storage::setConditionData($key, $data, $where);
		if (empty($result)) 
		{
			AC::$errorNo	=	'GMM003';
			return false;
		}
		$data['status'] == 0 && $this->diaryListCacheModel->addGroupUser($data['gid'], $data['uid']);
		$data['status'] == 1 && $this->diaryListCacheModel->removeGroupUser($data['gid'], $data['uid']);
		return true;
	}/*}}}*/

    /**
     * @param $gid
     * @param $start
     * @param $length
     * @param $count
     * @return bool|mixed
     */
	public function getGroupUsers($gid, $start, $length, $count)/*{{{*/
	{
		if (empty($gid))
		{
			AC::$errorNo    =   'GMM001';
			return FALSE;
		}
		$userNum = $this->diaryListCacheModel->getGroupUserNum($gid);
        //如果计数不对则更新圈子用户计数
        if(intval($userNum) != $count && $count < 500){
            $check = 1;
        }else{
            $check = 0;
        }
        //圈子信息
        $groupInfo  =   $this->grouInfoModel->groupAddRedis($gid);
        $uidList =  [];
        if(!empty($groupInfo['mUids'])) {
            $uidList = explode(',', $groupInfo['mUids']);
        }
        $userCount = 0;
		if(intval($userNum) < 1 || intval($userNum) < $count) {
		    //添加队长及管理
            $this->diaryListCacheModel->addGroupUser($gid, $groupInfo['uid'], '1767024002');
            if(!empty($uidList)){
                foreach ($uidList as $uid){
                    $this->diaryListCacheModel->addGroupUser($gid, $groupInfo['uid'], '1767024000');
                }
            }
            for ($i = 0; $i < 8; $i++) {
                $sql = "SELECT uid,time FROM xxtShare.groupusers_{$i} where gid = {$gid} and status = 0 and gtype = 1 ORDER BY time DESC LIMIT 0,100";
                $key = $this->groupMembersKeyPrefix . $i;
                $result = Storage::fetchDbSentenceByClient($key, $sql, 2);
                if (empty($result)) continue;
                foreach ($result as $key => $val) {
                    if($val['uid'] == $groupInfo['uid'] || in_array($val['uid'], $uidList)){
                        continue;
                    }
                    $this->diaryListCacheModel->addGroupUser($gid, $val['uid'], $val['time']);
                }
                if($check){
                    $where = array(
                        'gid'   =>  $gid,
                        'status'=>  0,
                        'gtype' =>  1,
                    );
                    $key = $this->groupMembersKeyPrefix . $i;
                    $num = Storage::countDataRow($key, $where);
                    $userCount += $num;
                }
            }
        }
        if($check && $userCount !=0){
            $data   =   array();
            $data['member_num']   =   $userCount + 1;

            $key    =   $this->groupKeyPrefix. 0;
            $where  =   array('gid' => $gid, 'gtype' => 1);
            Storage::changeNumValueAdd($key, $data, $where);
            $this->diaryListCacheModel->setGroupCount($gid, 'member_num', $userCount);
        }
        $len = $start + $length - 1;
        return $this->diaryListCacheModel->getGroupUser($gid, $start, $len);
	}/*}}}*/

	/**
	 * 用于判断是否加入过该圈子
	 * @param unknown $uid
	 * @param unknown $gid
	 * @return Ambigous <unknown, boolean, multitype:>
	 */
	private function getGroupMember($uid, $gid, $gtype)/*{{{*/
	{
		$where  =    array('uid'=>$uid,'gid'=>$gid,'gtype'=>$gtype);
			
		$orderBy=   ' time DESC ';
		$key    =   $this->groupMembersKeyPrefix. $uid;
		$result =   Storage::getConditionManyData($key, $where, $orderBy);
		return $result;
	}

	/**
	 * 查询用户加入圈子的数量
	 * @param unknown $uid
	 * @param unknown $gid
	 * @return Ambigous <unknown, boolean, multitype:>
	 */
	public function getUserGroupNum($uid)/*{{{*/
	{
		$where  =    array('uid'=>$uid, 'gtype'=>1);
		$key    =   $this->groupMembersKeyPrefix. $uid;
        $result =   Storage::countDataRow($key, $where);
		return $result ? $result : 0;
	}

	public function getUserGroupAllCache($uid) {
        if (empty($uid)) return array();
        $result = $this->diaryListCacheModel->getUserGroupAllCache($uid);
        // 查找加入的所有圈子
        if (empty($result) || intval($result['gtime']) < 1){
            $where  =    'uid='.$uid.' AND gtype=1';
            $orderBy=   ' time DESC ';
            $key    =   $this->groupMembersKeyPrefix. $uid;
            $data =   Storage::getConditionManyData($key, $where, $orderBy);
            // 组装返回数据
            if (!empty($data)){
                // $gtime为加入时间  $ftime为关注管理员时间
                $gtime = $ftime = 0;
                $gids = array();
                foreach ($data as $value){
                    if ($value['time'] > 0){
                        $gtime 	= $value['time'];
                    }
                    if ($value['ftime'] > 0){
                        $ftime 	= $value['ftime'];
                    }
                    if ($value['status'] == 0 && $value['gtype'] == 1){
                        $gids[] = $value['gid'];
                    }
                }
                $gidCache = '';
                if (count($gids) > 0){
                    $gidCache = implode(',',$gids);
                }
                $data = [
                    'gids'    =>    $gidCache,
                    'gtime'   =>    $gtime,
                    'ftime'   =>    $ftime
                ];
                $this->diaryListCacheModel->addGroupUserCache($uid, $data);
            }
        }
        //用户创建圈子数据
        if(!isset($result['createGid'])) {
            $key   =   $this->groupKeyPrefix. 0;
            $where =   array('uid' => $uid,'status'=>0,'gtype'=>1);
            $order = " time DESC";
            $result	   =   Storage::getConditionManyData($key, $where, $order);
            $createGid = array();
            if(!empty($result)) {
                foreach ($result as $val) {
                    $createGid[] = $val['gid'];
                }
            }
            $data = ['createGid' => ''];
            if(!empty($createGid)) {
                $data = [
                    'createGid' => implode(',', $createGid)
                ];
            }
            $this->diaryListCacheModel->addGroupUserCache($uid, $data);
        }
        $result = $this->diaryListCacheModel->getUserGroupAllCache($uid);
        //用户管理圈子数据
        if(!isset($result['manageGid']) || (empty($result['manageGid']) && !empty($result['gids']))) {
            $followGids = explode(',', $result['gids']);
            $manageGid = [];
            foreach ($followGids as $gid){
                $groupInfo = $this->grouInfoModel->groupAddRedis($gid);
                $uidList = [];
                if(!empty($groupInfo['mUids'])) {
                    $uidList = explode(',', $groupInfo['mUids']);
                }
                if(in_array($uid, $uidList)){
                    $manageGid[] = $gid;
                }
            }
            $data = ['manageGid' => ''];
            if(!empty($manageGid)) {
                $data = [
                    'manageGid' => implode(',', $manageGid)
                ];
            }
            $this->diaryListCacheModel->addGroupUserCache($uid, $data);
        }
        $userCacheInfo = $this->diaryListCacheModel->getUserGroupAllCache($uid);
        return $userCacheInfo;
    }

	//创建
	public function getUserCreateGroups($uid) {
        if (empty($uid)) return array();
        $result = $this->diaryListCacheModel->getUserGroupAllCache($uid);
        if(empty($result['createGid'])) {
            $key   =   $this->groupKeyPrefix. 0;
            $where =   array('uid' => $uid,'status'=>0,'gtype'=>1);
            $order = " time DESC";
            $result	   =   Storage::getConditionManyData($key, $where, $order);
            $createGid = array();
            if(!empty($result)) {
                foreach ($result as $val) {
                    $createGid[] = $val['gid'];
                }
            }
            $data = ['createGid' => ''];
            if(!empty($createGid)) {
                $data = [
                    'createGid' => implode(',', $createGid)
                ];
            }
            $this->diaryListCacheModel->addGroupUserCache($uid, $data);
        }
        $result = $this->diaryListCacheModel->getUserGroupAllCache($uid);
        return $result;
    }
    //管理
    public function getUserManageGroups($uid) {
	    if(empty($uid)) return array();
        $result = $this->diaryListCacheModel->getUserGroupAllCache($uid);
        if(!isset($result['manageGid']) && !empty($result['gids'])) {
            $followGids = explode(',', $result['gids']);
            $manageGid = [];
            foreach ($followGids as $gid){
                $groupInfo = $this->grouInfoModel->groupAddRedis($gid);
                $uidList = [];
                if(!empty($groupInfo['mUids'])) {
                    $uidList = explode(',', $groupInfo['mUids']);
                }
                if(in_array($uid, $uidList)){
                    $manageGid[] = $gid;
                }
            }
            $data = ['manageGid' => ''];
            if(!empty($manageGid)) {
                $data = [
                    'manageGid' => implode(',', $manageGid)
                ];
            }
            $this->diaryListCacheModel->addGroupUserCache($uid, $data);
        }
        $result = $this->diaryListCacheModel->getUserGroupAllCache($uid);
        return $result;
    }
	
	/**
	 * 获取关注的圈子
	 * @param  $uid
	 * @return string
	 */
	public function getUserGroups($uid){
	    if (empty($uid)) return array();
	    
		$result = $this->diaryListCacheModel->getUserGroupAllCache($uid);
		if (empty($result) || intval($result['gtime']) < 1){
		    // 查找加入的所有圈子
//			$where  =    array('uid'=>$uid);
			$where  =    'uid='.$uid.' AND gtype=1';
			$orderBy=   ' time DESC ';
			$key    =   $this->groupMembersKeyPrefix. $uid;
			$data =   Storage::getConditionManyData($key, $where, $orderBy);
			// 组装返回数据
			if (!empty($data)){
			    // $gtime为加入时间  $ftime为关注管理员时间
			    $gtime = $ftime = 0;
			    $gids = array();
			    foreach ($data as $value){
			        if ($value['time'] > 0){
			            $gtime 	= $value['time'];
			        }
			        if ($value['ftime'] > 0){
			            $ftime 	= $value['ftime'];
			        }
			        //if ($value['status'] == 0 && $value['gid'] <= AC::$groupMaxGid){
			        if ($value['status'] == 0 && $value['gtype'] == 1){
			            $gids[] = $value['gid'];
			        }
			    }
			    
			    // 返回数据
			    $result = array(
			            'gids'    =>    '',
			            'gtime'   =>    $gtime,
			            'ftime'   =>    $ftime
			    );
			    if (count($gids) > 0){
			        $result['gids'] = implode(',',$gids);
			    }
                $data = [
                    'gids'    =>    $result['gids'],
                    'gtime'   =>    $gtime,
                    'ftime'   =>    $ftime
                ];
                $this->diaryListCacheModel->addGroupUserCache($uid, $data);
			}
		}
		
		return  $result;
	}

    /**
     * 获取关注的话题
     * @param unknown $uid
     * @return string
     */
    public function getUserFollowTopics($uid){
        if (empty($uid)) return array();

        $result = $this->diaryListCacheModel->getUserFollowTopicsAllCache($uid);
        //TODO 数据问题，暂时刷新用户缓存来解决
        $result = [];
        if ($result){
            $result = array_keys($result);
        }else{
            $result = [];
            //$where  =    'uid='.$uid.' AND status=0 AND gid>='.AC::$diaryTopicCf['start_id'];
            $where  =    'uid='.$uid.' AND status=0 AND gtype=0';
            $orderBy=   ' time DESC ';
            $key    =   $this->groupMembersKeyPrefix. $uid;
            $data =   Storage::getConditionManyData($key, $where, $orderBy);
            if ($data){
                $this->diaryListCacheModel->rmUserFollowTopic($uid);
                $desc = 100;
                foreach ($data as $item) {
                    if($item['gid'] < 10000 ){
                        continue;
                    }
                    $this->diaryListCacheModel->addUserFollowTopic($uid, $item['gid'], $desc);
                    $desc --;
                    $result[] = $item['gid'];
                }
            }
        }

        return  $result;
    }
	
	/**
	 * 设置缓存
	 * @param unknown $uid
	 * @param unknown $gids
	 * @return boolean|multitype:multitype: string
	 */
	public function setUserGroupCache($uid, $gids){
	    if (empty($gids)){
	        return FALSE;
	    }
	    
	    $gtime = $ftime = AC::SERVER_TIME;
	    $data = array(
	            'gids'	=>	$gids,
	            'gtime'	=>	$gtime,
	            'ftime' =>  AC::SERVER_TIME
	    );
	    $this->diaryListCacheModel->addGroupUserCache($uid, $data);
	    	
	    $result = array();
	    $result['gids']  = explode(',', $gids);
	    $result['gtime'] = $gtime;
	    $result['ftime'] = $ftime;
	    return $result;
	}
	
	public function initUserGroups($uid, $gidsStr){
	    $gids = explode(',', $gidsStr);
	    $data = array();
	    foreach ($gids as $gid){
	        $data['gid'] = $gid;
	        $data['uid'] = $uid;
	        $data['gtype'] = 1;
	        $this->addMembers($data);
	    }
	    $this->initMember($gids);
	    
	    $gtime = $ftime = AC::SERVER_TIME;
	    $data = array(
	            'gids'	=>	$gidsStr,
	            'gtime'	=>	$gtime,
	            'ftime' =>  $ftime
	    );
	    $this->diaryListCacheModel->addGroupUserCache($uid, $data);
	    
	    $result = array();
	    $result['gids']  = $gids;
	    $result['gtime'] = $gtime;
	    $result['ftime'] = $ftime;
	    return $result;
	}

	// 添加默认圈子
	public function initMember($data)/*{{{*/
	{
		// 默认加入圈子列表,对应者圈子的id
		$list   =   implode(',',$data);
		$tmp    =   "gid in({$list})";
			
		$sql    =   " UPDATE xxtShare.group_0 SET member_num = member_num + 1 WHERE ".$tmp;
			
		$key    =   $this->groupKeyPrefix. 0;
		$result =   Storage::execDbSentence($key, $sql);
		return  $result;
	}/*}}}*/
	
	/**
	 * 更新ftime时间
	 * @param unknown $uid
	 * @return boolean
	 */
	public function initUpdateGroupUserFtime($uid){
	    if (intval($uid) < 1){
	        return FALSE;
	    }
	    
	    $data   =   array('ftime' => AC::SERVER_TIME);
	    $where  =   array('uid' => $uid);
	    $key    =   $this->groupMembersKeyPrefix. $uid;
		$result =   Storage::setConditionData($key, $data, $where);
		if (empty($result)){
			AC::$errorNo	=	'GMM003';
			return false;
		}
		return true;
	}
}